<template>
  <div class="system-config-container mx-auto p-8 max-w-7xl bg-white shadow-lg rounded-xl mt-10">
    <!-- 查询 -->
    <div class="search-container flex justify-end mb-6">
      <el-button
          @click="getSystemConfig"
          type="primary"
          class="search-button bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md shadow-md transition duration-300"
      >
        获取系统配置
      </el-button>
    </div>

    <!-- 错误信息 -->
    <div v-if="errorMessage" class="error-message text-red-500 text-center mb-6 text-lg font-semibold">
      {{ errorMessage }}
    </div>

    <!-- 系统配置表格 -->
    <el-form :model="systemConfig" class="system-config-form grid grid-cols-1 md:grid-cols-2 gap-6">
      <el-form-item label="店主信息及联系方式">
        <el-input v-model="systemConfig.ownerInfo" class="form-input border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500 block w-full"></el-input>
      </el-form-item>
      <el-form-item label="收款码设置">
        <div class="flex flex-col">
          <el-upload
              :action="uploadUrl"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :show-file-list="false"
              class="upload-demo"
          >
            <el-button size="small" type="primary" class="bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md shadow-md transition duration-300">
              上传收款码
            </el-button>
          </el-upload>
          <div v-if="systemConfig.paymentCodeUrl" class="mt-4">
            <img :src="systemConfig.paymentCodeUrl" alt="收款码" class="small-image rounded-md shadow-md">
          </div>
          <div v-else-if="systemConfig.paymentCode" class="mt-4">
            <img :src="`data:image/jpeg;base64,${byteArrayToBase64(systemConfig.paymentCode)}`" alt="收款码" class="small-image rounded-md shadow-md">
          </div>
        </div>
      </el-form-item>
      <el-form-item label="系统存储路径设置">
        <el-input v-model="systemConfig.storagePath" class="form-input border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500 block w-full"></el-input>
      </el-form-item>
      <el-form-item label="邮箱服务器">
        <el-input v-model="systemConfig.emailServer" class="form-input border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500 block w-full"></el-input>
      </el-form-item>
      <el-form-item label="邮箱用户名">
        <el-input v-model="systemConfig.emailUsername" class="form-input border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500 block w-full"></el-input>
      </el-form-item>
      <el-form-item label="邮箱密码">
        <el-input v-model="systemConfig.emailPassword" class="form-input border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500 block w-full"></el-input>
      </el-form-item>
      <el-form-item label="配送方式">
        <el-input v-model="systemConfig.deliveryMethod" class="form-input border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500 block w-full"></el-input>
      </el-form-item>
      <el-form-item label="配送收费">
        <el-input v-model="systemConfig.deliveryFee" class="form-input border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500 block w-full"></el-input>
      </el-form-item>
      <el-form-item label="第三方配送基础信息">
        <el-input v-model="systemConfig.thirdPartyDeliveryInfo" class="form-input border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500 block w-full"></el-input>
      </el-form-item>
      <el-form-item class="col-span-1 md:col-span-2 flex justify-end">
        <el-button type="primary" @click="updateSystemConfig" class="bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md shadow-md transition duration-300">
          保存配置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import http from '@/axios/http';

// 存放系统配置数据
let systemConfig = ref({});

// 报错提示
let errorMessage = ref("");

// 上传地址
let uploadUrl = ref('/upload_payment_code'); // 请替换为实际的上传地址

// 将字节数组转换为 base64 字符串的方法
const byteArrayToBase64 = (byteArray) => {
  const encoder = new TextEncoder('utf-8');
  const data = encoder.encode(String.fromCharCode(...new Uint8Array(byteArray)));
  return btoa(String.fromCharCode.apply(null, new Uint8Array(data)));
};

// 获取系统配置
function getSystemConfig() {
  http.post('/glsb/get_system_config').then((res) => {
    let result = res.data;
    if (result.result ==='success') {
      systemConfig.value = result.data;
    } else {
      errorMessage.value = result.error;
    }
  }).catch((error) => {
    console.error('获取系统配置失败:', error);
    errorMessage.value = '获取系统配置失败: ' + error.message;
  });
}

// 更新系统配置
function updateSystemConfig() {
  http.post('/glsb/update_system_config', systemConfig.value).then((res) => {
    let result = res.data;
    if (result.result ==='success') {
      errorMessage.value = '系统配置更新成功';
    } else {
      errorMessage.value = result.error;
    }
  }).catch((error) => {
    console.error('更新系统配置失败:', error);
    errorMessage.value = '更新系统配置失败: ' + error.message;
  });
}

// 上传成功回调
function handleUploadSuccess(response, file, fileList) {
  if (response.data && response.result === "success") {
    // 更新系统配置数据，以便页面显示新上传的收款码
    systemConfig.value = response.data;
  } else {
    errorMessage.value = response.error || "上传成功但未获取到有效数据";
  }
}

// 上传失败回调
function handleUploadError(error, file, fileList) {
  console.error('上传失败:', error);
  errorMessage.value = '上传收款码失败: ' + error.message;
}

// 上传前处理
function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    errorMessage.value = '上传图片只能是 JPG 格式!';
  }
  if (!isLt2M) {
    errorMessage.value = '上传图片大小不能超过 2MB!';
  }
  return isJPG && isLt2M;
}

// 页面初始化
onMounted(() => {
  getSystemConfig();
});
</script>

<style scoped>
.system-config-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-button {
  margin-right: 20px;
}

.error-message {
  color: #f56c6c;
  margin-bottom: 20px;
  text-align: center;
}

.system-config-form {
  width: 100%;
}

.form-input {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.upload-demo {
  margin-bottom: 10px;
}

.small-image {
  max-width: calc(360px); /* 宽度缩小到原来的六分之一 */
  height: calc(360px); /* 高度缩小到原来的六分之一 */
}
</style>